<script setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { userUpdatePasswordService } from '@/api/user.js' // 引入服务函数
import { useRouter } from 'vue-router'
const router = useRouter();

// 表单数据
const userPassword = ref({
  oldPwd: '',
  newPwd: '',
  rePwd: ''
})

// 表单验证规则
const rules = {
  oldPwd: [
    { required: true, message: '请输入旧密码', trigger: 'blur' },
    {
      pattern: /^\S{6,15}$/,
      message: '密码必须是6-15位的非空字符串',
      trigger: 'blur'
    }
  ],
  newPwd: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    {
      pattern: /^\S{6,15}$/,
      message: '密码必须是6-15位的非空字符串',
      trigger: 'blur'
    }
  ],
  rePwd: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      pattern: /^\S{6,15}$/,
      message: '密码必须是6-15位的非空字符串',
      trigger: 'blur'
    },
    {
      validator: (rule, value, callback) => {
        if (value && value !== userPassword.value.newPwd) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 使用ref来引用表单
const formRef = ref(null);

// 提交修改密码的函数
const updatePassword = async () => {
  // 通过 formRef 来访问表单实例
  formRef.value.validate(async (valid) => {
    if (valid) {
      // 如果表单验证通过，调用服务函数发送请求
      try {
        const passwordData = {
          old_pwd: userPassword.value.oldPwd,
          new_pwd: userPassword.value.newPwd,
          re_pwd: userPassword.value.rePwd
        };
        
        const result = await userUpdatePasswordService(passwordData);  // 调用 service 函数
        ElMessage.success(result.message? result.message:'修改成功,请重新登录')
        router.push('/login');  // 跳转到登录页
      } catch (error) {
        ElMessage.error(result.message? result.message:'修改成功')
      }
    } else {
      ElMessage.error('表单验证失败，请检查输入');
    }
  });
};
</script>

<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>修改密码</span>
      </div>
    </template>
    <el-row>
      <el-col :span="12">
        <el-form ref="formRef" :model="userPassword" :rules="rules" label-width="100px" size="large">
          <el-form-item label="旧密码" prop="oldPwd">
            <el-input v-model="userPassword.oldPwd" type="password"></el-input>
          </el-form-item>
          <el-form-item label="新密码" prop="newPwd">
            <el-input v-model="userPassword.newPwd" type="password"></el-input>
          </el-form-item>
          <el-form-item label="确认密码" prop="rePwd">
            <el-input v-model="userPassword.rePwd" type="password"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="updatePassword">提交修改</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </el-card>
</template>
